import arcade
import random

SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600

SQUARE_WIDTH = 40


def draw_square(x, y):
    arcade.draw_rectangle_filled(x, y, SQUARE_WIDTH, SQUARE_WIDTH, arcade.color.BROWN)


def on_draw(delta_time):
    arcade.start_render()
    draw_square(on_draw.start_x, on_draw.start_y)

    # 碰到边界反弹
    if on_draw.start_x <= SQUARE_WIDTH / 2 or on_draw.start_x >= SCREEN_WIDTH - SQUARE_WIDTH / 2:
        on_draw.dx = -on_draw.dx

    # 碰到边界反弹
    if on_draw.start_y <= SQUARE_WIDTH / 2 or on_draw.start_y >= SCREEN_HEIGHT - SQUARE_WIDTH / 2:
        on_draw.dy = -on_draw.dy

    # 变换方块的x， y坐标
    on_draw.start_x += on_draw.dx
    on_draw.start_y += on_draw.dy


# 给方块的一个随机的起始坐标, 为避免方块显示不全, 或显示在画布之外, 将范围限制在 1/2方块~最大宽度-1/2方块
on_draw.start_x = random.randint(SQUARE_WIDTH / 2, SCREEN_WIDTH - SQUARE_WIDTH / 2)
on_draw.start_y = random.randint(SQUARE_WIDTH / 2, SCREEN_HEIGHT - SQUARE_WIDTH / 2)
# 方块在x, y方向上的随机加速度
on_draw.dx = random.randint(4, 8)
on_draw.dy = random.randint(4, 8)


def main():
    arcade.open_window(SCREEN_WIDTH, SCREEN_HEIGHT, "Bouncing Square")
    arcade.set_background_color(arcade.color.ANTIQUE_WHITE)

    arcade.schedule(on_draw, 1 / 60)
    arcade.run()


if __name__ == "__main__":
    main()